define(function(require) {
  // load third-party javascript libraries
  var $ = require('jquery'),
      _ = require('underscore'),
      Backbone = require('backbone'),
  	  Selectize = require('selectize');

  // load project dependencies
  var StudyCollection = require('collections/studies');
  var SelectSampleSetsView = require('views/select_sample_sets');

  // define view
  var SelectStudyView = Backbone.View.extend({

  	initialize: function() {
      var self = this;      
  	  // initialize the view as a selectize.js control
  	  self.$el.selectize({
  	  	valueField: '_id',
        labelField: '_id',
        searchField: '_id',
        onChange: function(value) {
          console.log('onChange value: ' + value);
          console.log('onChange model: ' + JSON.stringify(self.collection.get(value)));
          self.trigger('change', self.collection.get(value));
        }
  	  });
      var selectizeEl = self.$el[0].selectize;
      selectizeEl.disable();
  	  // bind view to collection (add/remove)
  	  self.listenTo(self.collection, 'sync', self.render);
      self.listenTo(self.collection, 'remove', self.render);
      // load studies
      self.collection.fetch();
  	},

  	render: function() {
  	  // fetch the selectize instance
  	  var selectizeEl = this.$el[0].selectize;
  	  selectizeEl.clearOptions();
  	  // add each study as an option
  	  this.collection.each(function(model) {
  	  	selectizeEl.addOption({ _id: model.get('_id') });
  	  });
      selectizeEl.refreshOptions();
      selectizeEl.enable();
      return this;
    },

    currentStudy: function() {
      var self = this;
      var selectizeEl = self.$el[0].selectize;
      var value = selectizeEl.getValue();
      return self.collection.get(value);
    }

  });

  return SelectStudyView;
});